package com.hivis.sms;

import com.hivis.http.HttpRequestUtils;
import com.hivis.utils.DateTime;
import com.hivis.utils.MD5Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Set;

public class GXYSender{
    private static Logger logger = LoggerFactory.getLogger(GXYSender.class);
    private final static String SIGNATURE = "【广西信产】";


    protected static String name() {
        return "GXY";
    }


    public static SmsResult send(String phone,  String content) {
        JSONObject data = buildPackage2(phone, content); // 构造传递给短信平台的完成数据包
        SmsResult smsResult = sendSingle(data);
        return smsResult;
    }

    /**
     * 构造传递给短信平台的完成数据包
     * @param content
     * @return
     */
    private static JSONObject buildPackage(String phone, String content){
        // 构造传递给短信平台的完成数据包
        JSONObject param = new JSONObject();
        param.put("accountName", VipSmsConfig.ACCOUNT);

        JSONObject authorizationNode = new JSONObject();
        authorizationNode.put("Algorithm", "MD5");
        String date = DateTime.now().toDateTimeString();
        authorizationNode.put("Date", date);
        StringBuilder sb = new StringBuilder("MD5:");
        sb.append(VipSmsConfig.ACCOUNT).append(":")
                .append(VipSmsConfig.getPASSWORD()).append(":")
                .append(date);
        String hashhex = MD5Util.getMD5(sb.toString());
        authorizationNode.put("HASHHEX", hashhex);
        param.put("Authorization", authorizationNode);
        param.put("DestAddr", phone);
        param.put("SourceAddr", VipSmsConfig.sourceNumber);
        param.put("Content", SIGNATURE+content);
        param.put("ServiceCode", VipSmsConfig.serviceCode);

        return param;
    }
    /**
     * 构造传递给短信平台的完成数据包
     * @param content
     * @return
     */
    private static JSONObject buildPackage2(String phone, String content){
        // 构造传递给短信平台的完成数据包
        JSONObject param = new JSONObject();
        param.put("username", VipSmsConfig.ACCOUNT);
        param.put("password", VipSmsConfig.PASSWORD);
        param.put("phone", phone);
        param.put("message", content);
        param.put("subcode", "");
        param.put("orgaddr", "");

        return param;
    }

    private static SmsResult sendSingle(JSONObject content) {
        JSONObject result  = HttpRequestUtils.httpPost(VipSmsConfig.SERVER_IP + "/s/submitsm.do",content);

        logger.info("GXY result=" + result);

        if ("0".equals(result.get("result"))) {
            // 正常返回输出data包体信息（map）
            Set<String> keySet = result.keySet();
            for (String key : keySet) {
                Object object = result.get(key);
                logger.info(key + " = " + object);
            }
        } else {
            // 异常返回输出错误码和错误信息
            logger.error("错误码=" + result.get("result") + " 错误信息= " + result.get("msg"));
        }
        return mapToResult(result);
    }

    private static SmsResult mapToResult(Map<String, Object> result) {
        SmsResult requestResult = new SmsResult();
        requestResult.setSuccess(Boolean.FALSE);
        requestResult.setSenderName(name());
        if (result != null) {
            requestResult.setCode(result.get("result") + "");
            requestResult.setMsg(result.get("msg") + "");
            requestResult.setSmsid(result.get("MsgIDs") + "");
            if (Integer.valueOf(result.get("result").toString()) == 0) {
                requestResult.setSuccess(Boolean.TRUE);
            }
        }
        return requestResult;
    }
}
